package com.vieewer.btdemo.view.wifi;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.vieewer.btdemo.utils.CommonUtils;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

/**
 * Created by pyzhang on 18-8-31.
 */

public class FileTransferRunnable implements Runnable {

    private static final int SOCKET_PORT = 8888;
    private static final int SOCKET_TIMEOUT = 5000;

    private ServerSocket mServerSocket;
    private Socket mClientSocket;
    private static DataInputStream mInputStream;
    private static DataOutputStream mOutputStream;
    private boolean mExit = false;
    private boolean iSServer = false;
    private String mHostAddress = "";
    private Context mContext;
    private static Handler mHandler;
    private boolean mRunnableEnd = false;

    public FileTransferRunnable(Context context, boolean server, String ip, Handler handler) {
        mContext = context;
        iSServer = server;
        mHostAddress = ip;
        mHandler = handler;
        mExit = false;
    }

    public void exit() {
        mExit = true;
        releaseSocket();
    }

    public boolean getEndState() {
        return mRunnableEnd;
    }

    @Override
    public void run() {
        try {
            final File dirs = new File(Environment.getExternalStorageDirectory() + "/"
                    + mContext.getPackageName());
            if (!dirs.exists())
                dirs.mkdirs();

            if (iSServer) {
                mServerSocket = new ServerSocket(SOCKET_PORT);
                sendStatus("Server socket open,waiting for client connect");
                Log.d("111111", "Server: Socket opened");
                mClientSocket = mServerSocket.accept();
                sendStatus("Socket connected");
                Log.d("111111", "Server: connection done");
            } else {
                mClientSocket = new Socket();
                sendStatus("Client connecting server");
                mClientSocket.connect((new InetSocketAddress(mHostAddress, SOCKET_PORT)), 0);
                sendStatus("Client connected server");
                Log.d("111111", "Client socket - " + mClientSocket.isConnected());
            }
            mOutputStream = new DataOutputStream(mClientSocket.getOutputStream());
            mInputStream = new DataInputStream(mClientSocket.getInputStream());
            while (!mExit) {
                if (!receiveFile(mInputStream))
                    break;
            }
            releaseSocket();
        } catch (IOException e) {
            Log.e("111111", e.getMessage());
            releaseSocket();
        }
        Log.i("111111", "FileTransferRunnable --end");
        mRunnableEnd = true;
    }

    private void sendStatus(String str) {
        Message msg = new Message();
        msg.what = TransferPhotosManager.MSG_SET_STATUS;
        msg.obj = str;
        mHandler.sendMessage(msg);
    }

    public boolean receiveFile(DataInputStream inputStream) {
        byte buf[] = new byte[4096];
        long len;
        try {
            //获取文件长度
            len = inputStream.readLong();
            final File f = new File(Environment.getExternalStorageDirectory() + "/"
                    + mContext.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
                    + ".jpg");
            f.createNewFile();
            Log.d("111111", "server: copying files " + f.toString());
            OutputStream out = new FileOutputStream(f);
            int count = 0;
            for (long read = 0; read < len && count != -1; read += count) {
                long remain = len - read;
                int need = remain > 4096 ? 4096 : (int) remain;
                count = inputStream.read(buf, 0, need);
                out.write(buf, 0, count);
            }
            out.close();
            Message msg = new Message();
            msg.what = TransferPhotosManager.MSG_RECEIVE_FILE;
            msg.obj = f.getAbsolutePath();
            mHandler.sendMessage(msg);
        } catch (IOException e) {
            Log.d("111111", e.toString());
            return false;
        }
        return true;
    }

    public static void sendFile(File file) {
        if (mOutputStream == null)
            return;
//        File f = new File("mnt/sdcard/Pic");
        List<File> fileList = CommonUtils.getFile(file);


        for (int i = 0; i < fileList.size(); i++) {
            File file1 = fileList.get(i);


            Log.i("111111文件名字", fileList.get(i).getName());

            long len = fileList.get(i).length();
            try {
                mOutputStream.writeLong(len);
                FileInputStream inputStream = new FileInputStream(fileList.get(i));
                byte buf[] = new byte[4096];
                int count;
                while ((count = inputStream.read(buf)) != -1) {
                    mOutputStream.write(buf, 0, count);
                }
                inputStream.close();
                mHandler.sendEmptyMessage(TransferPhotosManager.MSG_SEND_FILE);
                Log.i("111111", "send file success:" + fileList.get(i).getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private void releaseSocket() {
        try {
            if (mInputStream != null) {
                mInputStream.close();
                mInputStream = null;
            }
            if (mOutputStream != null) {
                mOutputStream.close();
                mOutputStream = null;
            }
            if (mClientSocket != null) {
                mClientSocket.close();
                mClientSocket = null;
            }
            if (mServerSocket != null) {
                mServerSocket.close();
                mServerSocket = null;
            }
        } catch (IOException e) {
            Log.e("111111", e.getMessage());
        }
    }
}
